import * as React from "react";
import Divider from "@material-ui/core/Divider";
import './App.css'
import Button from "@material-ui/core/Button";
import TextField from "@material-ui/core/TextField";
import Dialog from "@material-ui/core/Dialog";
import DialogTitle from "@material-ui/core/DialogTitle";
import {AppBreadcrumbs} from "../../common/AppBreadcrumbs";
import Table from "@material-ui/core/Table";
import TableHead from "@material-ui/core/TableHead";
import TableRow from "@material-ui/core/TableRow";
import TableCell from "@material-ui/core/TableCell";
import TableBody from "@material-ui/core/TableBody";
import TablePagination from "@material-ui/core/TablePagination";
import DialogContent from "@material-ui/core/DialogContent";
import DialogActions from "@material-ui/core/DialogActions";
import DialogContentText from "@material-ui/core/DialogContentText";
import Link from "@material-ui/core/Link";
import {ServiceApi} from "../../../framework/api/ServiceApi";
import FormControl from "@material-ui/core/FormControl";
import InputLabel from "@material-ui/core/InputLabel";
import Input from "@material-ui/core/Input";
import FormHelperText from "@material-ui/core/FormHelperText";
import Select from "@material-ui/core/Select";
import MenuItem from "@material-ui/core/MenuItem";
import {Validations, Validator} from "../../../framework/Validator";
import {FormData} from '../../../framework/Validator'
import {BaseProps} from "../../../App";
import {AppConfirm} from "../../common/AppConfirm";
import {AppModel} from "../../model/AppModel";

interface AppListState {
    appList: Array<any>;
    addAppModal: boolean;
    tempApp: FormData;
}

interface AppListProp extends BaseProps {

}

export class AppList extends React.Component<AppListProp, AppListState> {

    breadcrumbs = [{
        name: '首页', path: '/home'
    }, {
        name: '应用管理', path: '/app'
    }];
    appTableHeader = [{title: 'name', name: '名称'}, {title: 'type', name: '类型'},
        {title: 'language', name: '语言'},
        {title: 'author', name: '创建人'}, {title: 'source', name: '源代码'}];

    tempAppInit: FormData = new FormData();

    tempApp: FormData = new FormData();

    constructor(props: AppListProp) {
        super(props);
        this.tempAppInit.set("name", {
            value: '',
            validators: [{name: Validations.REQUIRED, message: '不能为空', valid: true}]
        });
        this.tempAppInit.set("description", {value: ''});
        this.tempAppInit.set("type", {
            value: 'MICROSERVICE',
            validators: [{name: Validations.REQUIRED, message: '不能为空', valid: true}]
        });
        this.tempAppInit.set("language", {
            value: 'JAVA',
            validators: [{name: Validations.REQUIRED, message: '不能为空', valid: true}]
        });
        this.tempAppInit.set("source", {
            value: '',
            validators: [{name: Validations.REQUIRED, message: '不能为空', valid: true}]
        });
        this.tempAppInit.set("workspace", {value: ''});
        this.search = this.search.bind(this);
        this.addAppInputChange = this.addAppInputChange.bind(this);
        this.addSubmit = this.addSubmit.bind(this);
        this.cancelSubmit = this.cancelSubmit.bind(this);
        this.deleteApp = this.deleteApp.bind(this);
        this.state = {
            appList: [],
            addAppModal: false,
            tempApp: this.tempAppInit
        };
    }

    componentDidMount(): void {
        this.search();
    }

    search(event ?: any) {
        let keyword = '';
        if (event) {
            keyword = event.target.value;
        }
        ServiceApi.getAppList({keyword}).then(res => {
            this.setState({
                appList: res.data.result.content
            })
        });
    }

    addAppInputChange(event: any) {
        let fieldItem = this.state.tempApp.get(event.target.name);
        if (fieldItem === undefined) {
            return;
        }
        let formData = this.tempApp;
        fieldItem.value = event.target.value;
        formData.set(event.target.name, Validator.validation(fieldItem));
        this.setState({
            tempApp: formData
        });
    }

    addSubmit() {
        let result = Validator.validate(this.state.tempApp);
        if (Validator.hasError(result)) {
            this.setState({
                tempApp: result
            })
        } else {
            // 提交请求
            ServiceApi.createApp(Validator.getData(this.state.tempApp)).then(res => {
                this.setState({
                    tempApp: this.tempAppInit,
                    addAppModal: false
                });
                this.search();
            })
        }
    }

    cancelSubmit() {
        this.setState({
            addAppModal: false,
            tempApp: this.tempAppInit
        })
    }

    deleteApp(app: AppModel) {
        AppConfirm.open({
            title: '确认删除' + app.name + '项目ma？', onConfirm: () => {
                ServiceApi.deleteApp([app.id]).then(res => {
                    this.search();
                })
            }
        })
    };

    render() {
        return <div className={'main-content'}>
            <div>
                <AppBreadcrumbs breadcrumbs={this.breadcrumbs}
                                onClick={(path: any) => this.props.history.push(path)}
                />
                < Divider/>
                {/* 搜索表单 */}
                <div
                    className={'group-query-content'}>
                    <TextField className={'group-search'}
                               id="standard-search"
                               onChange={this.search}
                               label="搜索"
                               type="search"/>
                    <Button variant="contained"
                            color={'primary'}
                            onClick={() => {
                                this.setState({addAppModal: true})
                            }}>
                        新建应用 </Button>
                </div>
                <Dialog
                    onClose={() => this.setState({addAppModal: false})}
                    aria-labelledby="simple-dialog-title"
                    open={this.state.addAppModal}>
                    <DialogTitle id="simple-dialog-title"> 新建应用 </DialogTitle>
                    <DialogContent>
                        <DialogContentText>
                            每个应用在同一个集群中，可以拥有多个环境进行发布，每个环境支持多个节点发布，会按照指定的应用名 + 环境标识 + 节点编号进行构建命名,
                            不同环境由环境标识进行区分。
                        </DialogContentText>
                        <form
                            action="">
                            <FormControl
                                error={this.getError('name')}
                                required={true}
                                color={"primary"}
                                fullWidth={true}>
                                <InputLabel>应用名 </InputLabel>
                                < Input
                                    name={"name"}
                                    value={this.getValue('name')}
                                    onChange={this.addAppInputChange}
                                />
                                <FormHelperText> 字母 / 下划线 / 数字组成 </FormHelperText>
                            </FormControl>
                            <FormControl
                                color={"primary"}
                                fullWidth={true}>
                                <InputLabel>描述 </InputLabel>
                                < Input
                                    name={"description"}
                                    onChange={this.addAppInputChange}
                                    value={this.getValue('description')}
                                />
                                <FormHelperText> 200
                                    字符内 </FormHelperText>
                            </FormControl>
                            <FormControl
                                error={this.getError('source')}
                                required={true}
                                color={"primary"}
                                fullWidth={true}>
                                <InputLabel>代码源 </InputLabel>
                                < Input
                                    name={"source"}
                                    onChange={this.addAppInputChange}
                                    value={this.getValue('source')}
                                />
                                <FormHelperText> GIT代码源 </FormHelperText>
                            </FormControl>
                            <FormControl
                                error={this.getError('type')}
                                required={true}
                                color={"primary"}
                                fullWidth={true}>
                                <InputLabel>类型 </InputLabel>
                                <Select
                                    name={"type"}
                                    value={this.getValue('type')}
                                    onChange={this.addAppInputChange}>
                                    <MenuItem
                                        value={"MICROSERVICE"}> 微服务 </MenuItem>
                                </Select>
                            </FormControl>
                            <FormControl
                                error={this.getError('language')}
                                required={true}
                                color={"primary"}
                                fullWidth={true}>
                                <InputLabel>语言 </InputLabel>
                                <Select
                                    name={"language"}
                                    value={this.getValue('language')}
                                    onChange={this.addAppInputChange}>
                                    <MenuItem
                                        value={"JAVA"}> Java </MenuItem>
                                </Select>
                            </FormControl>
                            <FormControl
                                color={"primary"}
                                fullWidth={true}>
                                <InputLabel>工作空间 </InputLabel>
                                < Input
                                    name={"workspace"}
                                    value={this.getValue('workspace')}
                                    onChange={this.addAppInputChange}
                                />
                                <FormHelperText> 于代码源中的工作空间，默认位根目录 </FormHelperText>
                            </FormControl>
                        </form>
                    </DialogContent>
                    <DialogActions>
                        <Button
                            onClick={this.addSubmit}
                            variant="contained"
                            color="primary"> 创建 </Button>
                        <Button
                            onClick={this.cancelSubmit}
                            variant="contained"
                            color="default"> 取消 </Button>
                    </DialogActions>
                </Dialog>
                {/* 应用列表 */
                }
                <div
                    className={'group-list-content'}>
                    <Table
                        stickyHeader={true}>
                        <TableHead>
                            <TableRow>
                                {this.appTableHeader.map((item, index) => (
                                    <TableCell
                                        key={index}> {item.name}
                                    </TableCell>))}
                                <TableCell>操作</TableCell>
                            </TableRow>
                        </TableHead>
                        <TableBody>
                            {this.state.appList.map((app, index) => (
                                <TableRow
                                    hover
                                    key={index}>
                                    {
                                        this.appTableHeader.map((item, _index) => (
                                            <TableCell
                                                key={_index}>
                                                <ServiceTableCell
                                                    service={app}
                                                    history={this.props.history}
                                                    column={item}
                                                /></TableCell>
                                        ))
                                    }
                                    <TableCell>
                                        <Button onClick={() => this.deleteApp(app)} variant="outlined"
                                                color="secondary">删除</Button>
                                    </TableCell>
                                </TableRow>))}
                        </TableBody>
                    </Table>
                    <TablePagination
                        rowsPerPageOptions={[10, 25, 100]}
                        component="div"
                        count={this.state.appList.length}
                        rowsPerPage={10}
                        page={0}
                        onChangePage={() => {
                        }}
                        onChangeRowsPerPage={() => {
                        }}
                    />
                </div>
            </div>
        </div>
    }

    private getError(filedName: string) {
        let newVar = this.state.tempApp.get(filedName);
        if (newVar === undefined) {
            return false;
        }
        if (newVar.validators === undefined || newVar.validators.length === 0) {
            return false;
        }
        return newVar.validators[0].valid;
    }

    private getValue(fieldName: string) {
        let newVar = this.state.tempApp.get(fieldName);
        if (newVar === undefined) {
            return undefined;
        }
        return newVar.value;
    }
}

interface ServiceTableCellProp {
    column: any;
    service: any;
    history: any;
}

class ServiceTableCell
    extends React.Component<ServiceTableCellProp> {
    render() {
        switch (this.props.column.title) {
            case 'source':
                return (<Link component="button"
                              variant="body2"
                              href={this.props.service[this.props.column.title]}> {
                    this
                        .props.service[this.props.column.title]
                } </Link>);
            case 'name':
                return (<Link component="button"
                              variant="body2"
                              onClick={() => this.props.history.push('/app/' + this.props.service.id + '/build')}>
                    {
                        this.props.service[this.props.column.title]
                    }
                </Link>);
            default:
                return (<div>{this.props.service[this.props.column.title]} </div>);
        }
    }

}
